'use client';

import React, { useState, useEffect } from 'react';
import { 
  TextField, 
  Button, 
  Box, 
  Typography, 
  CircularProgress,
  InputAdornment,
  IconButton
} from '@mui/material';

interface PhoneVerificationFormProps {
  purpose: 'registration' | 'password_reset';
  onVerificationSuccess: (phone: string, code: string) => void;
}

const PhoneVerificationForm: React.FC<PhoneVerificationFormProps> = ({ 
  purpose,
  onVerificationSuccess 
}) => {
  const [phone, setPhone] = useState('');
  const [code, setCode] = useState('');
  const [countdown, setCountdown] = useState(0);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  useEffect(() => {
    if (countdown > 0) {
      const timer = setTimeout(() => setCountdown(countdown - 1), 1000);
      return () => clearTimeout(timer);
    }
  }, [countdown]);

  const validatePhone = () => {
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phone) {
      setError('请输入手机号');
      return false;
    }
    if (!phoneRegex.test(phone)) {
      setError('请输入有效的手机号');
      return false;
    }
    return true;
  };

  const handleSendCode = async () => {
    if (!validatePhone()) return;

    setLoading(true);
    setError('');
    setSuccess('');

    try {
      const response = await fetch('/api/auth/send-verification-code', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          phone,
          purpose
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || '发送验证码失败');
      }

      setSuccess('验证码已发送，请查收短信');
      setCountdown(60); // 60秒倒计时

      // 在开发环境中，如果返回了验证码，自动填充
      if (process.env.NODE_ENV === 'development' && data.code) {
        setCode(data.code);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : '发送验证码失败');
    } finally {
      setLoading(false);
    }
  };

  const handleVerify = () => {
    if (!validatePhone()) return;
    
    if (!code) {
      setError('请输入验证码');
      return;
    }

    // 调用父组件的成功回调
    onVerificationSuccess(phone, code);
  };

  return (
    <Box>
      <Box sx={{ mb: 2 }}>
        <TextField
          fullWidth
          label="手机号"
          value={phone}
          onChange={(e) => setPhone(e.target.value)}
          margin="normal"
          required
          InputProps={{
            endAdornment: (
              <InputAdornment position="end">
                <Button
                  onClick={handleSendCode}
                  disabled={countdown > 0 || loading}
                  sx={{ whiteSpace: 'nowrap' }}
                >
                  {loading ? (
                    <CircularProgress size={24} />
                  ) : countdown > 0 ? (
                    `${countdown}秒后重发`
                  ) : (
                    '发送验证码'
                  )}
                </Button>
              </InputAdornment>
            ),
          }}
        />
      </Box>

      <Box sx={{ mb: 2 }}>
        <TextField
          fullWidth
          label="验证码"
          value={code}
          onChange={(e) => setCode(e.target.value)}
          margin="normal"
          required
        />
      </Box>

      {error && (
        <Typography color="error" variant="body2" sx={{ mb: 2 }}>
          {error}
        </Typography>
      )}

      {success && (
        <Typography color="success.main" variant="body2" sx={{ mb: 2 }}>
          {success}
        </Typography>
      )}

      <Button
        fullWidth
        variant="contained"
        color="primary"
        onClick={handleVerify}
        disabled={!phone || !code || loading}
      >
        验证
      </Button>
    </Box>
  );
};

export default PhoneVerificationForm;
